<template>
  <CodeEditor v-model:value="strValue" language="json" />
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, watch } from 'vue'
import CodeEditor from './CodeEditor.vue'

export default defineComponent({
  name: 'JsonEditor',
  components: {
    CodeEditor
  },
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  emits: ['update:value'],
  setup(props, context) {
    let strValue
    const state = reactive({
      strValue: ''
    })

    watch(
      () => props.value,
      (val) => {
        if (typeof val === 'object') {
          strValue = JSON.stringify(val, null, 2)
        } else {
          strValue = val
        }
        state.strValue = strValue
      },
      { immediate: true }
    )
    watch(
      () => state.strValue,
      (val) => {
        if (!val) {
          context.emit('update:value', val)
          return
        }
        try {
          context.emit('update:value', JSON.parse(val))
        } catch (error) {
          console.log('json格式不正确，不保存')
        }
      },
    )
    return {
      ...toRefs(state)
    }
  }
})
</script>
